package com.kehutong.payment.service;

import com.kehutong.common.constant.CommonConstant;
import com.kehutong.payment.entity.MerchantSetting;
import com.kehutong.payment.entity.MerchantSettingCorp;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.orm.jdbc.execute.entity.FindPage;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MerchantSettingCorpService {

    @Inject
    private JdbcSession jdbcSession;

    public MerchantSettingCorp getDefaultByCompanyNo(String companyNo){
        return jdbcSession.findOne(MerchantSettingCorp.class)
                          .eq("companyNo", companyNo)
                          .eq("communityNo", "000000000000000000") // 项目编号，如果为000000000000000000，表示全部小区
                          .eq("auditStatus", true)
                          .eq("deleted", false)
                          .exe();
    }

    public MerchantSettingCorp getByCommunity(String companyNo, String communityNo){
        return jdbcSession.findOne(MerchantSettingCorp.class)
                          .eq("companyNo", companyNo)
                          .eq("communityNo", communityNo)
                          .eq("auditStatus", true)
                          .eq("deleted", false)
                          .exe();
    }

    /**
     * 商户分页
     * @param jsonObject
     * @return
     */
    public Page<MerchantSettingCorp> findPage(JSONObject jsonObject) {
        FindPage<MerchantSettingCorp> find = jdbcSession.findPage(MerchantSettingCorp.class);
        String communityNo=jsonObject.getString("communityNo");
        String companyNo=jsonObject.getString("companyNo");
        Boolean mchModel=jsonObject.getBoolean("mchModel");
        String mchId=jsonObject.getString("mchId");
        if(Objects.nonNull(companyNo)){
            find.eq("companyNo",companyNo);
        }
        if(Objects.nonNull(communityNo)){
            find.eq("communityNo",communityNo);
        }
        if(Objects.nonNull(mchModel)){
            find.eq("mchModel",mchModel);
        }
        if(Objects.nonNull(mchId)){
            Pattern r = Pattern.compile("^\\d+$");
            Matcher m = r.matcher(mchId);
            if(m.find()){
                find.like("mchId",mchId);
            }else{
                find.like("mchName",mchId);
            }
        }
        find.eq("deleted", false);
        find.order("sort", "DESC");
        find.order("createTime", "DESC");
        find.page(jsonObject);
        Page<MerchantSettingCorp>page = find.exe();
        page.getList().forEach(item->{
            List<String>ids=new ArrayList<String>();
            ids.add(item.getCompanyNo());
            ids.add(item.getCommunityNo());
            item.setCommunityIds(ids);
        });
        return page;
    }

    /**
     * 商户列表
     * @param jsonObject
     * @return
     */
    public List<MerchantSettingCorp> findList(JSONObject jsonObject) {
        return jdbcSession.findArray(MerchantSettingCorp.class)
                .eq("deleted", false)
                .eq(jsonObject,"companyNo")
                .eq(jsonObject,"auditStatus")
                .exe();
    }

    /**
     * 添加商户
     * @param corp
     * @return
     */
    public Object saveMerchant(MerchantSettingCorp corp){
        String communityName = corp.getCommunityName();
        if(org.coraframework.util.Objects.isEmpty(communityName)){
            throw new RuntimeException("项目名称不能为空.");
        }
        if(CommonConstant.DEFAULT_COMMUNITY_NAME.equals(communityName)){
            corp.setCommunityNo(CommonConstant.DEFAULT_COMMUNITY_NO);
            corp.setSort(999);
        }

        if(!corp.isMchModel()){
            List<MerchantSetting>merchantSettingList = jdbcSession.findArray(MerchantSetting.class).eq("deleted",false)
                    .eq("provider",true).exe();
            if(Objects.nonNull(merchantSettingList)){
                corp.setMerchantSettingId(merchantSettingList.get(0).getId());
            }
        }
        return jdbcSession.insert(corp);
    }

    /**
     * 修改商户
     * @param corp
     * @return
     */
    public Object updateMerchant(MerchantSettingCorp corp){
        if(!corp.isMchModel()){  //服务商模式
            if(Objects.isNull(corp.getMerchantSettingId())){
                List<MerchantSetting> merchantSettingList = jdbcSession.findArray(MerchantSetting.class).eq("deleted", false)
                        .eq("provider", true).exe();
                if (Objects.nonNull(merchantSettingList)) {
                    corp.setMerchantSettingId(merchantSettingList.get(0).getId());
                }
            }
            corp.setMchFileId(null);
            corp.setCertPemFileId(null);
            corp.setKeyPemFileId(null);
            corp.setAppId(null);
            corp.setMchSecret(null);
        }else{
            corp.setMerchantSettingId(null);
        }
        return jdbcSession.updateById(corp);
    }

    /**
     * 删除商户
     * @param id
     * @return
     */
    public Object deleteById(String id) {
        MerchantSettingCorp result = Pool.get(MerchantSettingCorp.class, id);
        if (result != null) {
            result.setDeleted(true);
            jdbcSession.updateById(result);
        }
        return 1;
    }

}
